import request from '@/utils/request'

export default {
  // 获取所有用户
  async getUsers () {
    try {
      const response = await request.get('/api/users')
      const rawData = Array.isArray(response) ? response : [response]
      return rawData.map(user => ({
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        gender: user.gender,
        avatar: user.avatar,
        createTime: user.createTime,
        role: user.roles?.[0]?.name?.replace('ROLE_', '') || 'user',
        enabled: user.enabledStatus === 1
      }))
    } catch (error) {
      console.error('获取用户失败:', error)
      return []
    }
  },

  async searchByUsername (username) {
    try {
      const response = await request.get('/api/users/search', {
        params: { username }
      })
      const rawData = Array.isArray(response) ? response : [response]
      return rawData.map(user => ({
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        gender: user.gender,
        avatar: user.avatar,
        createTime: user.createTime,
        role: user.roles?.[0]?.name?.replace('ROLE_', '') || 'user',
        enabled: user.enabledStatus === 1
      }))
    } catch (error) {
      console.error('搜索用户失败:', error)
      return []
    }
  },

  // 创建用户
  async createUser (userData) {
    const roleIds = userData.role === 'admin' ? [1] : [2]
    return request.post('/api/users', {
      username: userData.username,
      email: userData.email,
      phone: userData.phone,
      gender: userData.gender,
      password: userData.password,
      roleIds: roleIds,
      enabled: userData.enabled ? 1 : 0
    })
  },

  // 更新用户
  async updateUser (id, userData) {
    const roleIds = userData.role === 'admin' ? [1] : [2]
    return request.put(`/api/users/${id}`, {
      username: userData.username,
      email: userData.email,
      phone: userData.phone,
      gender: userData.gender,
      roleIds: roleIds,
      enabled: userData.enabled ? 1 : 0
    })
  },

  // 删除用户
  async deleteUser (id) {
    return request.delete(`/api/users/${id}`)
  },

  async getCurrentUser () {
    try {
      const response = await request.get('/api/users/my-account')
      const user = response.data || response
      return {
        id: user.id,
        username: user.username,
        email: user.email,
        phone: user.phone,
        gender: user.gender,
        avatar: user.avatar,
        role: user.roles?.[0]?.name?.replace('ROLE_', '') || 'user',
        createTime: user.createTime
      }
    } catch (error) {
      console.error('获取当前用户信息失败:', error)
      throw error
    }
  }
}
